﻿using CL_Helpers;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataFileApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
            Program.OpenFile += (obj) =>
            {
                jsonBinding = new JsonTreeViewTrans();
                string str = CL_Json.LoadJsonFromFile(obj, out string mes);
                jsonBinding.JsonBindingToTreeView(str, treeView1);
            };
        }

      

        JsonTreeViewTrans jsonBinding;
        public TreeNode nodeInDrag = null;
        private TreeNode tempNode = null;


        private void 默认位置加载_Click(object sender, EventArgs e)
        {
            jsonBinding = new JsonTreeViewTrans();

            string str = CL_Json.LoadJsonFromFile(@"default.json", out string mes);
            jsonBinding.JsonBindingToTreeView(str, treeView1);

        }
        private void 本地加载_Click(object sender, EventArgs e)
        {
            jsonBinding = new JsonTreeViewTrans();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "json文件|*.json|所有文件|*.*";
            openFileDialog.Multiselect = false;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string str = CL_Json.LoadJsonFromFile(openFileDialog.FileName, out string mes);
                jsonBinding.JsonBindingToTreeView(str, treeView1);
            }
        }

        private void 保存到默认位置_Click(object sender, EventArgs e)
        {
            //   string str = jsonBinding.DynamicCreatePropertyMesBody(treeView1);
            //CL_Json.SaveJsonToFile(@"default.json", str, out string mes);
        }
        private void 保存到本地_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Json文件|*.json|所有文件|*.*";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (toolStripMenuItem2.Checked)
                {
                    var o = jsonBinding.TransTreeViewToArray(treeView1.Nodes);
                    string js = CL_Json.EntityToJSON(o);
                    CL_Json.SaveJsonToFile(saveFileDialog.FileName, js, out string mes);
                }
                else
                {
                    string str = jsonBinding.DynamicCreatePropertyMesBody(treeView1);
                    CL_Json.SaveJsonToFile(saveFileDialog.FileName, str, out string mes);
                }

            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            nodeInDrag = treeView1.SelectedNode;
            if (nodeInDrag.Nodes.Count == 0)
            {
                dataGridView1.Rows.Clear();
                string name = string.Empty;
                string value = string.Empty;
                for (int i = 0; i < jsonBinding.LsNodeInfos.Count; i++)
                {
                    if (jsonBinding.LsNodeInfos[i].CurrentNode.Text == nodeInDrag.Text && jsonBinding.LsNodeInfos[i].CurrentNode.Level == nodeInDrag.Level && jsonBinding.LsNodeInfos[i].CurrentNode.Index == nodeInDrag.Index && jsonBinding.LsNodeInfos[i].CurrentNode.FullPath == nodeInDrag.FullPath)
                    {
                        name = nodeInDrag.Text;
                        ////value = jsonBinding.LsNodeInfos[i].NodeValue;
                        value = jsonBinding.LsNodeInfos[i].CurrentNode.Tag.ToString();
                    }
                }
                dataGridView1.Rows.Add(new string[] { name, value });
            }
            else
            {
                dataGridView1.Rows.Clear();
                foreach (TreeNode item in nodeInDrag.Nodes)
                {
                    if (item.Nodes.Count == 0)
                    {
                        string name = string.Empty;
                        string value = string.Empty;
                        for (int i = 0; i < jsonBinding.LsNodeInfos.Count; i++)
                        {
                            if (jsonBinding.LsNodeInfos[i].CurrentNode.Text == item.Text && jsonBinding.LsNodeInfos[i].CurrentNode.Level == item.Level && jsonBinding.LsNodeInfos[i].CurrentNode.Index == item.Index && jsonBinding.LsNodeInfos[i].CurrentNode.FullPath == item.FullPath)
                            {
                                name = item.Text;
                                //// value = jsonBinding.LsNodeInfos[i].NodeValue;
                                value = jsonBinding.LsNodeInfos[i].CurrentNode.Tag.ToString();
                            }
                        }
                        dataGridView1.Rows.Add(new string[] { name, value });
                    }
                }
            }
        }


        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                Point Click = new Point(e.X, e.Y);
                TreeNode CurrentNode = treeView1.GetNodeAt(Click);

                if (CurrentNode == null)
                    return;
                treeView1.SelectedNode = CurrentNode;
                nodeInDrag = CurrentNode;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 添加一级节点_Click(object sender, EventArgs e)
        {
            TreeNode newNode = new TreeNode("请设置一级节点名称");
            treeView1.Nodes.Add(newNode);
            jsonBinding.CreatNewNode(newNode, "");
        }

        private void 添加子级节点_Click(object sender, EventArgs e)
        {
            if (treeView1.Nodes.Count < 1)
            {
                return;
            }
            if (nodeInDrag == null)
            {
                return;
            }
            TreeNode newNode = new TreeNode("请设置子级节点名称");
            nodeInDrag.Nodes.Add(newNode);
            jsonBinding.CreatNewNode(newNode, "");
            nodeInDrag.Expand();
        }

        TreeNode waitDelNode;

        private void 编辑节点名称_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                treeView1.LabelEdit = true;
                treeView1.SelectedNode.BeginEdit();
                waitDelNode = treeView1.SelectedNode;

            }
        }

        private void 删除节点_Click(object sender, EventArgs e)
        {
            NodeInfo node = new NodeInfo();
            for (int i = 0; i < jsonBinding.LsNodeInfos.Count; i++)
            {
                var Ftp = jsonBinding.LsNodeInfos.Where(t => t.CurrentNode.Text == nodeInDrag.Text && t.CurrentNode.Level == nodeInDrag.Level && t.CurrentNode.Index == nodeInDrag.Index && t.CurrentNode.Parent?.Text == nodeInDrag.Parent?.Text);
                if (Ftp.Any())
                {
                    jsonBinding.LsNodeInfos.Remove(Ftp.FirstOrDefault());
                }
            }
            treeView1.Nodes.Remove(nodeInDrag);
            nodeInDrag = null;
        }

        private void 折叠所有节点_Click(object sender, EventArgs e)
        {
            treeView1.CollapseAll();
        }

        private void 展开所有节点_Click(object sender, EventArgs e)
        {
            treeView1.ExpandAll();
        }


        //节点编辑完成
        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {

            TreeNode vv = sender as TreeNode;
            TreeNode vvv = e.Node;
            treeView1.SelectedNode.EndEdit(true);
            treeView1.LabelEdit = false;

            //var node = jsonBinding.LsNodeInfos.Where(t => t.CurrentNode == waitDelNode);
            //if (node.Any())
            //{
            //    jsonBinding.LsNodeInfos.Remove(node.FirstOrDefault());
            //}


            jsonBinding.CreatNewNode(treeView1.SelectedNode, "");
        }

        private void UpdataEdit(TreeNode treeNode)
        {
            try
            {
                if (treeNode == null)
                {
                    return;
                }
                //判断是否有子节点
                if (treeNode.Nodes.Count == 0)  //无子节点，选中的为单个节点
                {
                    if (treeNode.Text == dataGridView1.Rows[0].Cells[0].Value.ToString())
                    {
                        for (int i = 0; i < jsonBinding.LsNodeInfos.Count; i++)
                        {
                            if (jsonBinding.LsNodeInfos[i].CurrentNode.Text == treeNode.Text
                                && jsonBinding.LsNodeInfos[i].CurrentNode.Level == treeNode.Level
                                && jsonBinding.LsNodeInfos[i].CurrentNode.Index == treeNode.Index
                                && jsonBinding.LsNodeInfos[i].CurrentNode.FullPath == treeNode.FullPath)
                            {
                                ////jsonBinding.LsNodeInfos[i].NodeValue = dataGridView1.Rows[0].Cells[1].Value.ToString();
                                jsonBinding.LsNodeInfos[i].CurrentNode.Tag = dataGridView1.Rows[0].Cells[1].Value.ToString();
                            }
                        }
                    }
                }
                else   //treeNode有子节点
                {
                    //遍历子节点
                    for (int j = 0; j < treeNode.Nodes.Count; j++)
                    {
                        //判断子节点是否有子节点, 无子节点就保存当前节点数据
                        if (treeNode.Nodes[j].Nodes.Count == 0)
                        {
                            if (treeNode.Nodes[j].Text == dataGridView1.Rows[j].Cells[0].Value.ToString())
                            {
                                for (int i = 0; i < jsonBinding.LsNodeInfos.Count; i++)
                                {
                                    if (jsonBinding.LsNodeInfos[i].CurrentNode.Text == treeNode.Nodes[j].Text
                                        && jsonBinding.LsNodeInfos[i].CurrentNode.Level == treeNode.Nodes[j].Level
                                        && jsonBinding.LsNodeInfos[i].CurrentNode.Index == treeNode.Nodes[j].Index
                                        && jsonBinding.LsNodeInfos[i].CurrentNode.FullPath == treeNode.Nodes[j].FullPath)
                                    {
                                        ///jsonBinding.LsNodeInfos[i].NodeValue = dataGridView1.Rows[j].Cells[1].Value.ToString();
                                        jsonBinding.LsNodeInfos[i].CurrentNode.Tag = dataGridView1.Rows[j].Cells[1].Value.ToString();
                                    }
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 点击新的节点时，保存上个节点数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            var t = treeView1.SelectedNode;
            UpdataEdit(t);
        }

        private void 粘贴为子节点_Click(object sender, EventArgs e)
        {
            if (tempNode == null)
            {
                return;
            }
            string name = null;
            Rename rename = new Rename();
            rename.sendName = (t) => { name = t; };
            rename.ShowDialog();
            tempNode.Text = "Array" + name;


            nodeInDrag.Nodes.Add(tempNode);
            //jsonBinding.CreatNewNode(tempNode, "");
            jsonBinding.AddNewNodes(tempNode);
            nodeInDrag.Expand();
            tempNode = null;
        }

        private void 复制节点_Click(object sender, EventArgs e)
        {
            tempNode = nodeInDrag.Clone() as TreeNode;
        }



        private void 粘贴为同级节点_Click(object sender, EventArgs e)
        {

            string name = null;
            Rename rename = new Rename();
            rename.sendName = (t) => { name = t; };
            rename.ShowDialog();
            tempNode.Text = "Array" + name;
            if (tempNode == null)
            {
                return;
            }

            nodeInDrag.Parent.Nodes.Add(tempNode);
            //jsonBinding.CreatNewNode(tempNode, "");
            jsonBinding.AddNewNodes(tempNode);
            nodeInDrag.Expand();
            tempNode = null;

        }

        //判断是否给NC用
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (toolStripMenuItem2.Checked)
            {
                string[] dateType = new string[] { "Boolean", "Integer", "Floating point number", "String", "(Process) Free Signal", "(Process)Signal", "(Process)Identifier" };
                DataType.Items.Clear();
                DataType.Items.AddRange(dateType);

                string[] modbusType = new string[] { "Discrete Input", "Input Register", "Coil", "Holding Register" };
                ModubusType.Items.Clear();
                ModubusType.Items.AddRange(modbusType);
            }
            else
            {
                DataType.Items.Clear();
                DataType.Text = "";
                ModubusType.Items.Clear();
                ModubusType.Text = "";
            }

        }


        int index;

        private void ControlVisible(string controlName, string value)
        {
            bool isTextbox = true;
            foreach (Control item in groupBox1.Controls)
            {
                if (item.GetType() != typeof(Label))
                {
                    if (item.Name == controlName)
                    {
                        item.Enabled = true;
                        item.Text = value;
                        isTextbox = false;
                    }
                    else
                    {
                        item.Enabled = false;
                    }
                }
            }

            textBox1.Enabled = isTextbox;
            textBox1.Text = isTextbox ? value : "";
            button1.Enabled = true;
        }

        private void SetValue()
        {
            foreach (Control item in groupBox1.Controls)
            {
                if (item.GetType() != typeof(Label) && item.GetType() != typeof(Button) && item.Enabled)
                {
                    dataGridView1.Rows[index].Cells[1].Value = item.Text;
                    item.Enabled = false;
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            SetValue();
            treeView1_BeforeSelect(null, null);
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //判断当前单元格
            index = e.RowIndex;

            string controlName = dataGridView1.Rows[index].Cells[0].Value.ToString();
            string value = dataGridView1.Rows[index].Cells[1].Value.ToString();
            ControlVisible(controlName, value);
        }
    }
}
